<!-- 需求列表  -->
<template>
  <pageHeader title="车间计划" :breadCrumb="['生产管理', '车间计划']" />
  <a-tabs
    v-model:activeKey="searchForm.workShopId"
    @change="() => tableRef.loadData()"
  >
    <a-tab-pane :key="0" title="全部" />
    <a-tab-pane
      v-for="item in workshopList"
      :key="item.id"
      :title="item.name"
    />
  </a-tabs>
  <div class="search-box">
    <a-space>
      <a-week-picker
        v-model="nowDate"
        value-format="Date"
        :day-start-of-week="1"
      />
    </a-space>
    <a-space>
      <a-button type="outline" @click="resetting">
        <template #icon> <icon-refresh /> </template>重置
      </a-button>
      <HeaderSettingCopy
        v-model:headerValues="headerValues"
        :define-headers="PlanWorkShopHerders.herders"
        :type="PlanWorkShopHerders.type"
      />
    </a-space>
  </div>
  <tableTurn style="padding: 10px" :tableData="getDemandAll" ref="tableRef">
    <a-table-column :width="70" align="center" title="序号">
      <template #cell="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
    </a-table-column>
    <a-table-column
      v-for="header in headerValues"
      :key="header.name"
      :width="header.width || 200"
      :title="header.name"
      :fixed="header.fixed"
      :data-index="header.code"
      align="center"
      :ellipsis="true"
      :tooltip="{
        position: 'top',
      }"
    >
      <template #cell="{ record }" v-if="!header.code">
        <template v-if="header.name === '紧急等级'">
          <a-typography-text type="primary" v-if="record.emergencyLevel === 1">
            一般
          </a-typography-text>
          <a-typography-text bold v-if="record.emergencyLevel === 2">
            紧急
          </a-typography-text>
          <a-typography-text type="warning" v-if="record.emergencyLevel === 3">
            加急
          </a-typography-text>
          <a-typography-text type="danger" v-if="record.emergencyLevel === 4">
            特急
          </a-typography-text>
        </template>
        <template v-if="header.name === '车间/factory/set/resources计划数量'">
          {{
            record.data?.reduce((val: number, { number }: any) => {
              return val + (number || 0);
            }, 0)
          }}
        </template>
      </template>
    </a-table-column>
    <a-table-column
      :title="Dayjs(nowDate).format('YYYY 年 MM 月')"
      align="left"
    >
      <a-table-column
        v-for="(item, index) in dayList"
        :key="index"
        :width="120"
        align="center"
        :title="item.toDate().getDate() + '号'"
      >
        <template #title>
          <div>{{ item.toDate().getDate() + '号' }}</div>
          <div>{{
            ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][item.day()]
          }}</div>
        </template>
        <template #cell="{ record }">
          {{ getNumber(item, record.data || []) }}
        </template>
      </a-table-column>
    </a-table-column>
    <a-table-column :width="150" fixed="right" title="操作" align="center">
      <template #cell="{ record }">
        <a-space>
          <!-- <a-link > 新建生产排程 </a-link> -->
          <a-tooltip content="新建生产排程">
            <IconFont
              type="icon-add-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="addScheduling(record)"
            />
          </a-tooltip>
          <!-- <a-popconfirm
              content="是否删除该数据?"
              type="error"
              @ok="del(record.id)"
            >
              <a-link status="danger"> 删除 </a-link>
            </a-popconfirm> -->
        </a-space>
      </template>
    </a-table-column>
  </tableTurn>
</template>

<script lang="ts" setup>
  import { reactive, onMounted, ref, computed } from 'vue';
  import { useRouter } from 'vue-router';
  import {
    GwtPlanWorkShopPage,
    AddProduceScheduling,
  } from '@/api/produce-management/OrderPlanning';
  import Dayjs from 'dayjs';
  import { PlanWorkShopHerders } from '@/utils/tableHerders';
  import {
    GetWorkshopPage,
    GetProductProcessRoutePage,
    GetProductBomPage,
    GetProductBom,
    GetdFactorySet,
  } from '@/api/FactoryModeling';
  import { TWorkshop } from '@/api/FactoryModeling/type';
  import { Message } from '@arco-design/web-vue';

  const router = useRouter();
  let searchForm = reactive<any>({});
  const tableRef = ref();
  let nowDate = ref<Date | undefined>();
  const addScheduling = async (data: any) => {
    let formData = {
      emergencyLevel: data.emergencyLevel,
      processGroupId: data.processGroupId,
      processGroupName: data.processGroupName,
      startDate: data.startDate,
      productionLineId: data.productionLineId,
      produceNumber: data.produceNumber,
      capacity: data.capacity,
      workShopId: data.workShopId,
      workShopPlanId: data.id,
      workShopName: data.workShopName,
      workOrderId: data.workOrderId,
      produceId: data.produceId,
      outputProductId: 0,
      planNumber:
        data.data?.reduce((val: number, { number }: any) => {
          return val + (number || 0);
        }, 0) || 0,
      inputMaterials: [],
      deviceData: [],
      lineData: [],
      stationData: [],
    };
    let getData1 = async () => {
      let productProcessRoute = ((
        await GetProductProcessRoutePage({
          page: 1,
          size: -1,
          history: 1,
          productId: data.produceId,
        })
      )?.content || [])[0];

      let groupItem = productProcessRoute?.groupData[data.sortIndex];
      formData.outputProductId = groupItem?.managementId;
      return Promise.resolve();
    };
    let getData2 = async () => {
      let bomData = ((
        await GetProductBomPage({
          page: 1,
          size: -1,
          historyState: 1,
          productId: data.produceId,
        })
      )?.content || [])[0];
      if (bomData?.id) {
        let bomDetails = await GetProductBom({ id: bomData?.id });
        bomDetails?.productBomDetail?.forEach(
          ({ productGroupData, productBomDetail }: any) => {
            if (
              productGroupData.some((item: any) => {
                return (
                  data.processGroupId ===
                    item.productGroupData.processGroupId &&
                  item.sortIndex === data.sortIndex
                );
              })
            ) {
              if (productBomDetail?.management?.id) {
                formData.inputMaterials.push(
                  productBomDetail?.management?.id as never
                );
              }
            }
          }
        );
      }
      return Promise.resolve();
    };
    await Promise.all([getData1(), getData2()]);
    // if (!formData.outputProductId) {
    //   return Message.error('输出物料为空');
    // }
    await AddProduceScheduling({
      ...formData,
      emergencyLevel: data.emergencyLevel,
      // inputMaterials: formData.inputMaterials.join('-'),
      // deviceData: formData.deviceData.join('-'),
      // lineData: formData.lineData.join('-'),
      // stationData: formData.stationData.join('-'),
    });

    setTimeout(() => {
      router.push({
        name: 'ProductionScheduling',
      });
    }, 500);
  };

  const getDemandAll = async (page: any) => {
    try {
      let res = await GwtPlanWorkShopPage({
        ...page,
        ...searchForm,
      });
      return Promise.resolve(res);
    } catch (err: unknown) {
      return Promise.reject();
    }
  };

  const Search = () => {
    tableRef.value.loadData();
  };
  const resetting = () => {
    for (const key in searchForm) {
      delete searchForm[key];
    }
    tableRef.value.loadData();
  };
  const del = async (id: number) => {
    // await DelStation({ id });
    tableRef.value.loadData();
  };

  let headerValues = ref<any[]>([]);
  let workshopList = ref<TWorkshop[]>([]);
  let getWorkshopPage = async () => {
    workshopList.value =
      (
        await GetWorkshopPage({
          page: 1,
          size: -1,
          state: 2,
        })
      )?.content || [];
  };
  getWorkshopPage();
  let getNumber = (dateItem: any, list: any[]) => {
    return list.find(({ date }) => {
      if (!date) return false;
      return dateItem.isSame(Dayjs(date), 'day');
    })?.number;
  };

  let dayList = computed(() => {
    let { type } = searchForm;
    let list = [];
    let getNowDate = Dayjs(nowDate.value);
    let day = getNowDate.day();
    let startDate = day
      ? getNowDate.subtract(day, 'd')
      : getNowDate.add(day, 'd');
    for (let i = 0; i < 7; i += 1) {
      list.push(startDate.add(i + 1, 'd'));
    }
    return list;
  });
</script>

<style scoped lang="less">
  .search-box {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 0px 10px;
  }
  :deep(.arco-space-item) {
    margin-top: 10px;
  }

  :deep(.arco-tabs-content) {
    padding-top: 0px;
  }
</style>
